﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace Rizmar
{
    public partial class LoginForm : Form
    {
        static string cnStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        static SqlConnection cn = new SqlConnection(cnStr);

        MainForm referrer;

        public LoginForm()
        {
            InitializeComponent();
        }

        public LoginForm(MainForm refer)
        {
            referrer = refer;
            InitializeComponent();
        }

        private void LoginButton_Click(object sender, EventArgs e)
        {
            cn.Open();
            bool entradaPermitida = false;

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Usuario] WHERE usuario = '" + UsernameTextBox.Text + "' AND senha = '" + geramd5(PasswordTextBox.Text) + "'", cn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows) entradaPermitida = true;
                dr.Close();
            }
            if (!entradaPermitida)
                MessageBox.Show("Login ou senha errados.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            else
            {
                /* seta o parâmetro usuário do MainForm e retorna OK */
                bool isAdmin;
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Usuario] WHERE usuario = '" + UsernameTextBox.Text + "' AND senha = '" + geramd5(PasswordTextBox.Text) + "'", cn))
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    isAdmin = bool.Parse(dr["admin"].ToString());
                    // MessageBox.Show(isAdmin.ToString());
                }
                Usuario user = new Usuario(UsernameTextBox.Text, isAdmin);
                referrer.SetUser(user);
                this.DialogResult = DialogResult.OK;
            }
            cn.Close();
        }

        private void ExitButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        public string geramd5(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
                sb.Append(hash[i].ToString("x2"));
            return sb.ToString();
        }
    }
}
